package service

import (
	"github.com/clakeboy/golib/components"
	"github.com/gin-gonic/gin"
	"urs_service/middles"
	"urs_service/router"
)

type HttpServer struct {
	server  *gin.Engine
	isDebug bool
	isCross bool
	addr    string
}

func NewHttpServer(addr string, isDebug bool, isCross, isPProf bool) *HttpServer {
	server := &HttpServer{isCross: isCross, isDebug: isDebug, addr: addr}
	server.Init()
	if isPProf {
		server.StartPprof()
	}
	return server
}

func (h *HttpServer) Start() {
	wait := make(chan bool)
	go func() {
		err := h.server.Run(h.addr)
		if err != nil {
			wait <- true
		}
	}()
	<-wait
}

func (h *HttpServer) Init() {
	if h.isDebug {
		gin.SetMode(gin.DebugMode)
	} else {
		gin.SetMode(gin.ReleaseMode)
	}

	h.server = gin.New()

	//使用中间件
	if h.isDebug {
		h.server.Use(gin.Logger(), gin.Recovery())
	} else {
		h.server.Use(middles.Logger(), middles.Recovery())
	}

	h.server.Use(middles.Cache())
	h.server.Use(middles.BoltDatabase())
	h.server.Use(middles.Cookie())
	h.server.Use(middles.SQLite())
	//h.server.Use(gzip.Gzip(gzip.DefaultCompression))
	//h.server.Use(middles.Session())
	//跨域调用的OPTIONS
	h.server.OPTIONS("*action", func(c *gin.Context) {
		components.Cross(c, h.isCross, c.Request.Header.Get("Origin"))
	})

	//POST服务接收
	h.server.POST("/service/:controller/:action", func(c *gin.Context) {
		components.Cross(c, h.isCross, c.Request.Header.Get("Origin"))
		controller := router.GetController(c.Param("controller"), c)
		components.CallAction(controller, c)
	})
	//GET服务
	h.server.GET("/service/:controller/:action", func(c *gin.Context) {
		components.Cross(c, h.isCross, c.Request.Header.Get("Origin"))
		controller := router.GetController(c.Param("controller"), c)
		components.CallActionGet(controller, c)
	})

	//H5端入口
	//h.server.GET("/app/:action", func(context *gin.Context) {
	//	controller := controllers.NewDefaultController(context)
	//	components.CallActionGet(controller, context)
	//})

	//静态文件API接口
	h.server.Static("/app/", "./assets/app")
	//设置模板文件目录
	//h.server.SetFuncMap(template.FuncMap{"unescaped": func(str string) template.HTML { return template.HTML(str) }})
	//h.server.LoadHTMLGlob("./assets/templates/*")
}

func (h *HttpServer) StartPprof() {
	components.InitPprof(h.server)
}
